/*
 *  Copyright 2013 Utkin Dmitry
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#include <QMap>
#include <QSet>
#include <QTcpServer>
#include <QTcpSocket>
#include <QSignalMapper>
#include <QDebug>
#include <google/protobuf/service.h>
#include <google/protobuf/descriptor.h>
#include "SocketRpcServer.h"
#include "SocketRpcServerSession.h"

namespace protoqtrpc
{

class SocketRpcServerPrivate
{
public:
    quint16 port;
    QTcpServer tcpServer;
    QMap<std::string, google::protobuf::Service*> services;
    QSet<SocketRpcServerSession*> sessions;
    QSignalMapper signalMapper;
};


SocketRpcServer::SocketRpcServer():
    d_ptr(new SocketRpcServerPrivate)
{
    d_ptr->port = 0;
    connect(&d_ptr->tcpServer, SIGNAL(newConnection()), SLOT(acceptConnection()));
    connect(&d_ptr->signalMapper, SIGNAL(mapped(QObject*)), SLOT(closeConnection(QObject*)),
            Qt::DirectConnection);
}

SocketRpcServer::~SocketRpcServer()
{
    delete d_ptr;
}

void SocketRpcServer::setPort(quint16 port)
{
    d_ptr->port = port;
}

quint16 SocketRpcServer::port() const
{
    return d_ptr->port;
}

bool SocketRpcServer::registerService(::google::protobuf::Service* service)
{
#ifdef QT_DEBUG
    qDebug() << "Registering service " <<
                service->GetDescriptor()->full_name().c_str();
#endif
    d_ptr->services[service->GetDescriptor()->full_name()] = service;
    return true;
}

::google::protobuf::Service* SocketRpcServer::getService(const std::string& serviceName)
{
    QMap<std::string, google::protobuf::Service*>::const_iterator service =
            d_ptr->services.find(serviceName);

    if (service == d_ptr->services.end())
        return NULL;

    return service.value();
}

bool SocketRpcServer::start()
{
    return d_ptr->tcpServer.listen(QHostAddress::Any, d_ptr->port);
}

void SocketRpcServer::acceptConnection()
{
    QTcpSocket* sock = d_ptr->tcpServer.nextPendingConnection();
    SocketRpcServerSession* session = new SocketRpcServerSession(sock, this);

    d_ptr->sessions.insert(session);
    d_ptr->signalMapper.setMapping(sock, session);
    connect(sock, SIGNAL(disconnected()), &d_ptr->signalMapper, SLOT(map()));
}

void SocketRpcServer::stop()
{
    d_ptr->tcpServer.close();
}

QString SocketRpcServer::errorString() const
{
    return d_ptr->tcpServer.errorString();
}

void SocketRpcServer::closeConnection(QObject* obj)
{
    SocketRpcServerSession* session = qobject_cast<SocketRpcServerSession*>(obj);
    if (session != NULL)
    {
        d_ptr->sessions.remove(session);
        delete session;
    }
}

}
